package com.efrei.uchat.server.strategies;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.io.Session;
import com.efrei.uchat.message.Message;
import com.efrei.uchat.message.TextMessage;
import com.efrei.uchat.model.croom.Croom;
import com.efrei.uchat.model.croom.Crooms;
import com.efrei.uchat.server.UChatServer;

public class TextWorker implements MessageStrategy {

	private static final Logger logger = Logger.getLogger(TextWorker.class);
	
	@Override
	public List<Message> manage(Message message, UChatServer context) throws UChatException {
		List<Message> ret = new ArrayList<Message>();
		
		TextMessage textMsg = (TextMessage) message;
		int id = message.getSessionId();
		
		// lock sessions
		try {
			context.getSessionsLock().lock();
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new UChatException("error while blocking sessions lock");
		}
		Session session = context.getSessions().getSession(message.getSessionId());
		
		// lock crooms
		try {
			context.getCroomsLock().lock();
		} catch (InterruptedException e) {
			e.printStackTrace();
			throw new UChatException("error while blocking crooms lock");
		}
		
		try {
			// get croom
			Crooms crooms = context.getCrooms();
			Croom croom = crooms.getCroom(textMsg.getCroom());
			if(croom==null) {
				// unknown croom => does nothing
				StringBuilder bb = new StringBuilder();
				bb.append("Message from user ")
					.append(session.toString())
					.append(" in invalid croom ")
					.append(textMsg.getCroom());
				logger.error(bb.toString());
				return ret;
			}
			
			logger.debug("send text message to all clients in "+
								croom.getTopic()+
								" with "+croom.getNbSessions()+" users.");
			logger.debug("MESSAGE: "+textMsg.getText());
			
			// send message for all sessions in croom
			TextMessage retMessage;
			for (Session registered : croom.getSessions()) {
				retMessage = new TextMessage(
						textMsg.getText(),
						croom.getTopic(),
						// author
						id,
						session.getChatter().getPseudo(),
						// receiver
						registered.getId());
				ret.add(retMessage);
			}
		} finally {
			context.getCroomsLock().unlock();
			context.getSessionsLock().unlock();
		}
		
		logger.debug("Message send to "+ret.size()+" clients");
		return ret;
	}

}
